def main():
    # 读取输入
    n, m = map(int, input().split())
    a = [0] + list(map(int, input().split()))  # 序列a，从1开始索引
    b = [0] + list(map(int, input().split()))  # 序列b，从1开始索引

    # 初始化DP数组
    dp = [[0] * (m + 1) for _ in range(n + 1)]

    # 动态规划求解
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if a[i] == b[j]:
                # 当前元素相等，长度加1
                dp[i][j] = dp[i-1][j-1] + 1
            else:
                # 当前元素不等，取上方或左方的最大值
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])

    # 输出结果
    print(dp[n][m])

    # # 使用滚动数组优化
    # dp = [0] * (m + 1)
    # prev = [0] * (m + 1)
    # for i in range(1, n + 1):
    #     for j in range(1, m + 1):
    #         if a[i] == b[j]:
    #             dp[j] = prev[j - 1] + 1
    #         else:
    #             dp[j] = max(prev[j], dp[j - 1])
    #     # 更新prev数组
    #     prev = dp[:]
    # # 输出结果
    # print(dp[m])

if __name__ == "__main__":
    main()
